/**
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY. See the GNU General Public License for more details. Copyright (C) 2011 CellObject.net
 */
package net.cellobject.sqlitexmlbrowser.shared;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

public class FileUtil {
	public static List<IResource> getAllProjectFiles(final IProject project) {
		List<IResource> result = new ArrayList<IResource>();
		if (project == null) {
			return result;
		}
		try {
			result = collectFiles(project.members(), result);
		} catch (final CoreException e) {
		}
		return result;
	}

	private static List<IResource> collectFiles(final IResource[] members, final List<IResource> result) throws CoreException {
		// recursively collect files for the given members
		for (final IResource res : members) {
			if (res instanceof IFolder) {
				collectFiles( ((IFolder)res).members(), result);
			} else if (res instanceof IFile) {
				result.add(res);
			}
		}
		return result;
	}

	public static void copyDirectoryOrFile(final File sourceLocation, final File targetLocation) {
		try {
			if (sourceLocation.isDirectory()) {
				if (!targetLocation.exists()) {
					targetLocation.mkdir();
				}
				final String[] children = sourceLocation.list();
				for (final String element : children) {
					copyDirectoryOrFile(new File(sourceLocation, element), new File(targetLocation, element));
				}
			} else {
				final InputStream in = new FileInputStream(sourceLocation);
				final OutputStream out = new FileOutputStream(targetLocation);
				// Copy the bits from input stream to output stream
				final byte[] buf = new byte[1024];
				int len;
				while ( (len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				in.close();
				out.close();
			}
		} catch (final IOException e) {
			Logger.logError(e);
		}
	}

	public static void removeDirectoryOrFile(final File targetLocation) {
		if ( (targetLocation != null) && targetLocation.exists()) {
			targetLocation.delete();
		}
	}
}
